<script setup>
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref } from 'vue';
import easyapi from '../api';
import * as echarts from 'echarts';
    //定义绑定的数据
    const tableData=ref([]);
    //控制新增信息窗口是否显示
    const addWinVisible=ref(false);
     //控制编辑信息窗口是否显示
     const editWinVisible=ref(false);
    //新增数据绑定对象
    const addObject=ref({});
    //编辑数据绑定对象
    const editObject=ref({});
    //查询数据的文本
    const checkObj=ref({
      size:5,
      page:1
    });
    //关联bill数据
    const billObj=ref([]);
    //关联ticket数据
    const ticketObj=ref([]);
    const total=ref(90);
    //记录修改数据的下标
    var editIndex=-1;  
    //下拉框获取数据
    const getBillTicket=async function(){
        let resultBill=await easyapi.get("/api/getbill");
        let resultTicket=await easyapi.get("/api/getticket");
        billObj.value=resultBill.data;
        ticketObj.value=resultTicket.data;
    }
    //挂载页面时查询数据
    onMounted(async function() {
        await checkData();
        await getBillTicket();
        drawChart(); // 绘制图表
    });

    const del=function(index,row){
        ElMessageBox.confirm(
    '确定删除该行信息吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async function(){
        //提交数据
        let result=await easyapi.del("/api/consumptionrecord",row.id);
        if(result.code==200){
          //刷新表格数据
        tableData.value.splice(index,1);
        //提示删除成功
        ElMessage({
        type: 'success',
        message: '删除成功',
      })
        }else{
          ElMessage({
        type: 'info',
        message: result.message,
      })
        }
        
      })
    }
    //显示窗口
    const openAddWin=()=>{
        addObject.value={};
        addWinVisible.value=true;
    }
    const closeAddWin=()=>{
        addWinVisible.value=false;
    }
    //保存新增数据 addObject
    const addSave = async function() {
    try {
        // 表单验证
        for (const key in addObject.value) {
            if (!addObject.value[key]) {
                ElMessage({
                    type: 'warning',
                    message: `${key} 不能为空`,
                });
                return; // 阻止继续执行
            }
        }
        // 调整日期
        const selectedDate = new Date(addObject.value.time);
        selectedDate.setDate(selectedDate.getDate() + 1);
        addObject.value.time = selectedDate.toISOString().split('T')[0];
        // 发送请求
        const result = await easyapi.postJson("api/consumptionrecordjson", addObject.value);

        if (result && result.data) {
            //tableData.value.unshift(result.data);

            // 表格数据变更
            ElMessage({
                type: 'success',
                message: '保存成功',
            });
            checkData();
            // 提示成功后关闭窗口
            closeAddWin();
        } else {
            // 处理无数据的情况
            ElMessage({
                type: 'error',
                message: '保存失败，请重试',
            });
        }
    } catch (error) {
        // 捕获并处理请求中的错误
        console.error('保存失败:', error);
        ElMessage({
            type: 'error',
            message: '保存失败，请确保新增数据是否完整且合规。',
        });
    }
}
    //点击编辑按钮执行的方法
    const edit=function(index,row){
        //记录修改数据的下标
        editIndex=index;
        //绑定要修改的数据
        editObject.value.id=row.id;
        editObject.value.billid=row.billid;
        editObject.value.ticketid=row.ticketid;
        editObject.value.actualprice=row.actualprice;
        editObject.value.number=row.number;
        //打开对话框
        editWinVisible.value=true;
    }
    //保存编辑数据
    const editSave=async function(){   
      for (const key in editObject.value) {
            if (!editObject.value[key]) {
                ElMessage({
                    type: 'warning',
                    message: `${key} 不能为空`,
                });
                return; // 阻止继续执行
            }
        }    
        //发送请求
        let result=await easyapi.putJson("/api/consumptionrecordjson",editObject.value);
        //刷新表格
        tableData.value[editIndex]=result.data;
        checkData();
        //提示       
        ElMessage({
        type: 'success',
        message: '保存成功',
        });
        editWinVisible.value=false;
    }
    const checkData=async function(val){
      //点击分页按钮
      if(typeof val == 'number'){
        checkObj.value.page=val;
      }
        //查询数据
        let result=await easyapi.get("/api/consumptionrecord",checkObj.value);
        //更新表格数据
        tableData.value=result.data.list;
        total.value=result.data.count;
    };
</script>


<template>
  <div class="flex items-center gap-4">
    <el-select
      v-model="checkObj.billid"
      placeholder="请选择票务"
      size="large"
      style="width: 240px"
    >
    <el-option
      :label="'请选择'"
      :value="null"
    />
      <el-option
        v-for="item in billObj"
        :label="`${item.name} - ${item.discount}`"
        :value="item.id"
      />
    </el-select>
    <el-select
      v-model="checkObj.ticketid"
      placeholder="请选择票据"
      size="large"
      style="width: 240px"
    >
    <el-option
      :label="'请选择'"
      :value="null"
    />
      <el-option
        v-for="item in ticketObj"
        :label="`${item.name} - ${item.price}`"
        :value="item.id"
      />
    </el-select>
    <el-button type="primary" @click="checkData">查询</el-button>
    <el-button type="success" @click="openAddWin">新增</el-button>
  </div>
    <el-table
        :data="tableData"
        style="width: 100%"
        :row-class-name="tableRowClassName"
    >
    <!-- <el-table-column prop="id" label="ID"/> -->
    <el-table-column prop="bill.name" label="票务名称"/>
    <el-table-column prop="bill.discount" label="票务折扣"  />
    <el-table-column prop="ticket.name" label="票据名称" />
    <el-table-column prop="ticket.price" label="票据价格"  />
    <el-table-column prop="actualprice" label="实际价格" />
    <el-table-column prop="number" label="数量" />
    <el-table-column prop="time" label="时间" />
    <el-table-column label="操作" width="240">
        <template #default="scope">
            <el-button type="danger" @click="del(scope.$index,scope.row)">
            删除</el-button>
            <el-button type="warning" @click="edit(scope.$index,scope.row)">
                编辑</el-button>
        </template>
    </el-table-column>
    </el-table>
    <!-- current-page分页组件初始显示的页码  size每页的条数--> 
    <el-pagination 
    :page-size="checkObj.size"
    :current-page="checkObj.page"
    background layout="prev, pager, next" :total="total"  @current-change="checkData" />
    
    <div id="chartContainer" style="width: 100%; height: 400px;"></div>

    <!-- start新增信息的弹出框-->
    <el-dialog v-model="addWinVisible" title="新增信息" width="500">
        <el-form :model="addObject">
          <el-form-item label="票务名称" :label-width="80">  
            <el-select
                v-model="addObject.billid"
                placeholder="请选择"
              >
            <el-option
              v-for="item in billObj"
              :label="`${item.name} - ${item.discount}`"
              :value="item.id"
            /></el-select>        
          </el-form-item>
      <el-form-item label="票据名称" :label-width="80">
        <el-select
                v-model="addObject.ticketid"
                placeholder="请选择"
        >
        <el-option
              v-for="item in ticketObj"
              :label="`${item.name} - ${item.price}`"
              :value="item.id"
            />
      </el-select>
      </el-form-item>
      <!-- <el-form-item label="真实价格" :label-width="80">
        <el-input v-model="addObject.actualprice" autocomplete="off" placeholder="新建添加若不填写默认为0"/>
      </el-form-item> -->
      <el-form-item label="数量" :label-width="80">
        <el-input v-model="addObject.number" autocomplete="off" placeholder="新建添加若不填写默认为0"/>
      </el-form-item>
      <el-form-item label="时间" :label-width="80">
        <el-date-picker
          v-model="addObject.time"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          :clearable="true"
        ></el-date-picker>
      </el-form-item>
        </el-form>
        <template #footer>
      <div class="dialog-footer">
        <el-button @click="addWinVisible = false">取消</el-button>
        <el-button type="primary" @click="addSave">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- end新增信息的弹出框-->
    <!-- start编辑信息的弹出框-->
    <el-dialog v-model="editWinVisible" title="编辑关联信息" width="500">
      <el-form :model="editObject">
        <!-- <el-form-item label="票务名称" :label-width="80">  
            <el-select
                v-model="editObject.billid"
                placeholder="请选择"
              >
            <el-option
              v-for="item in billObj"
              :label="`${item.name} - ${item.discount}`"
              :value="item.id"
            /></el-select>        
          </el-form-item>
      <el-form-item label="票据名称" :label-width="80">
        <el-select
                v-model="editObject.ticketid"
                placeholder="请选择"
        >
        <el-option
              v-for="item in ticketObj"
              :label="`${item.name} - ${item.price}`"
              :value="item.id"
            />
      </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="真实价格" :label-width="80">
        <el-input v-model="editObject.actualprice" autocomplete="off" />
      </el-form-item> -->
      <el-form-item label="数量" :label-width="80">
        <el-input v-model="editObject.number" autocomplete="off" />
      </el-form-item>
        </el-form>
        <template #footer>
      <div class="dialog-footer">
        <el-button @click="editWinVisible = false">取消</el-button>
        <el-button type="primary" @click="editSave">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- end编辑信息的弹出框--> 
</template>
<style></style>